package com.dyh.quickdemo.whenThen;

import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;

/*
@Author=Joey Wheeler
@Date=2021/3/5 16:15
*/
public class IfOp<T> {
    private final T val;
    private  Predicate<T> predicate;

    private static final IfOp<?> END = new IfOp<>(null,e->false);


    private IfOp(T val){
        this.val = val;
    }

    private IfOp(T val,Predicate<T> predicate){
        this.val = val;
        this.predicate = predicate;
    }

    public static <T>IfOp<T> from(T val){
        return new IfOp<>(val);
    }

    public IfOp<T> when(Predicate<T> predicate){
        if (!this.equals(END))
            this.predicate = predicate;
        return this;
    }

    public <U> IfOp<U> then(Function<? super T,? extends U> mapper){
        Objects.requireNonNull(mapper);
        if (this.val==null)
            return (IfOp<U>) END;
        if (this.predicate==null || this.predicate.test(val))
            return IfOp.from(mapper.apply(val));
        return (IfOp<U>) END;
    }

    public T orElse(T other){
        return END.equals(this)?other:this.val;
    }

}
